# -*- coding: utf-8 -*-
import pickle

class LoadCPU:
      def __init__(self, cpu):
	    self.lastCPUsum3 = 0
	    self.lastCPUsum4 = 0
	    self.cpu = cpu
  
      def ReturnLoad(self):
	    myfile =  open ("/proc/stat", 'r')
	    text = myfile.read()
	    myfile.close()
	    jobsumm = self.ReturnLex(text,1) + self.ReturnLex(text, 2) + self.ReturnLex(text, 3)
	    allsumm = self.ReturnLex(text,1) + self.ReturnLex(text, 2) + self.ReturnLex(text, 3) + self.ReturnLex(text, 4)  
	    cpuload =  float(jobsumm - self.lastCPUsum3)/float(allsumm- self.lastCPUsum4)
	    self.lastCPUsum3 = jobsumm
	    self.lastCPUsum4 = allsumm
	    cputext = str(cpuload*100)
	    i=0
	    while cputext[i] != ".":
		  i+=1
	    cputext = cputext[0:i+3] + " %"
	    return cputext
    
      def ReturnLex(self, text, num):
	    vC = text.find(self.cpu)
	    while text[vC] == " ":
		  vC += 1
	    i = 0
	    j = vC
	    while i <= num: 
		  while text[j] == " ":
			  j+=1
		  while text[j] == "\n":
			  j+=1
		  beg = j
		  while text[j] != " ":
			  if text[j] == "\n":
			      break
			  j+=1
		  i+=1
	    myText = text[beg: j]
	    myText.strip()
	    return float(myText)